package com.pcbly.web.persistence.resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.pcbly.web.Constants;
import com.pcbly.web.bean.system.AuthorityBean;
import com.pcbly.web.bean.system.ResourceBean;
import com.pcbly.web.persistence.HibernateBaseDao;

public class ResourceHibernateDao extends HibernateBaseDao<ResourceBean>
		implements ResourceDao {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8063695629920541359L;

	public ResourceHibernateDao() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected Class<ResourceBean> getEntityClass() {
		return ResourceBean.class;
	}

	@SuppressWarnings("unchecked")
	public List<ResourceBean> findBy(Map<String, String> filter)
			throws Exception {
		// TODO Auto-generated method stub
		Criteria criteria = getEntityCriteria();

		String id = filter.get("id");
		if (StringUtils.isNotEmpty(id))
			criteria.add(Restrictions.eq("id", id));

		String name = filter.get("name");
		if (StringUtils.isNotEmpty(name))
			criteria.add(Restrictions.like("name", "%" + name + "%"));

		String module = filter.get("module");
		if (StringUtils.isNotEmpty(module) && !"all".equals(module))
			criteria.createAlias("module", "m").add(
					Restrictions.eq("m.id", module));

		String resString = filter.get("resString");
		if (StringUtils.isNotEmpty(resString))
			criteria.add(Restrictions.like("resString", "%" + resString + "%"));

		String resType = filter.get("resType");
		if (StringUtils.isNotEmpty(resType) && !"all".equals(resType))
			criteria.add(Restrictions.eq("resType", resType));

		// 察看是否已授权
		String permissionId = filter.get("permissionId");
		if (StringUtils.isNotEmpty(permissionId)) {
			AuthorityBean permis = getAuthorityBeanById(permissionId);

			String authorize = filter.get("authorize");
			if (StringUtils.isNotEmpty(authorize) && !"all".equals(authorize)) {
				List<String> ids = new ArrayList<String>();
				for (ResourceBean resource : permis.getResources()) {
					ids.add(resource.getId());
				}
				if (!ids.isEmpty()) {
					if (authorize.equals(Constants.STATUS_AUTH)) {
						criteria.add(Restrictions.in("id", ids.toArray()));
					} else {
						criteria.add(Restrictions.not(Restrictions.in("id", ids
								.toArray())));
					}
				}
			}
		}

		criteria.addOrder(org.hibernate.criterion.Order.asc("id"));

		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public AuthorityBean getAuthorityBeanById(String id) throws Exception {
		String hsql = "from AuthorityBean where id=:id";
		List<AuthorityBean> list = getHibernateTemplate().find(hsql,
				new Object[] { id });
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}
	}
}
